﻿using Padsurface.Audio.Song.Model;
using Padsurface.Audio.Song.Repositories.Interfaces;
using Padsurface.Audio.Song.Services.Interfaces;
using System;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;

namespace Padsurface.Audio.Song.Services
{
    [Export(typeof(ISongSaver))]
    internal class SongSaver : ISongSaver
    {
        private readonly ISongRepository _songRepository;

        [ImportingConstructor]
        public SongSaver(ISongRepository songRepository)
        {
            if (songRepository == null) throw new ArgumentNullException("songRepository");

            _songRepository = songRepository;
        }

        public async Task Save(Model.Song song, StorageFile storageFile)
        {
            if (song == null) throw new ArgumentNullException("song");
            if (storageFile == null) throw new ArgumentNullException("storageFile");

            var serializableSong = new SerializableSong
            {
                Id = song.Id,
                Name = song.Name,
                SoundFilePaths = song.Sounds.Select(s => s.WaveFileOutput.FilePath).ToList(),
                BeatsPerMinute = song.BeatsPerMinute,
                IsLoopEnabled = song.IsLoopEnabled,
                Timeline = song.Timeline.Select(s => new SerializableRecordedSound { Beat = s.Beat, SoundFilePath = s.Sound.WaveFileOutput.FilePath }).ToList()
            };

            await _songRepository.Save(serializableSong, storageFile);
        }
    }
}